package server;

import Events.EventFactory;
import shared.Consts;
import shared.PlayerPortfolio;
import java.util.concurrent.PriorityBlockingQueue;
import network.NetQProxy;
import packet.Command;
import packet.CommandRequest;
import packet.Request;
import packet.TriggeredEventReq;

/**
 * Node to hold player game data
 * @author Joel Garboden
 */
public class PlayerNode
{
  private NetQProxy proxy;
  private PlayerPortfolio portfolio;
  private EventFactory eventFactory;

  private int ID;

  /**
   * Constructor
   * @param ID player's ID
   * @param proxy player proxy
   * @param portfolio player portfolio
   * @param eventFactory
   */
  public PlayerNode(int ID, NetQProxy proxy, PlayerPortfolio portfolio, EventFactory eventFactory)
  {
    this.ID = ID;
    this.proxy = proxy;
    this.portfolio = portfolio;
    this.eventFactory = eventFactory;
  }

  /**
   * Mutator
   * @param active proxy status
   */
  public void setActive(boolean active)
  {
    proxy.setActive(active);
  }

  /**
   * Accessor
   * @return proxy status
   */
  public boolean isActive()
  {
    return proxy.isActive();
  }

  /**
   * Adds a command to the outgoing queue
   * @param cmd command to be sent
   */
  public void send(Command cmd)
  {
    proxy.queue.add(cmd);
  }

  /**
   * Mutator
   * @param name player name
   */
  public void setName(String name)
  {
    portfolio.setName(name);
  }

  /**
   * Accessor
   * @return player name
   */
  public String getName()
  {
    return portfolio.getName();
  }

  /**
   * Accessor for the players portfolio
   * @return player's portfolio
   */
  public PlayerPortfolio getPortfolio()
  {
    return portfolio;
  }

  /**
   * Mutator for portfolio
   * @param portfolio new player portfolio
   */
  public void setPortfolio(PlayerPortfolio portfolio)
  {
    this.portfolio = portfolio;
  }

  /**
   * Advances player data by one week.
   * @param gameQ game's processing queue
   * @param game
   */
  public void nextWeek(PriorityBlockingQueue<CommandRequest> gameQ, Game game)
  {
    portfolio.nextWeek();
    portfolio.payBills();
    Request req = null;

    if(portfolio.weekCounter % Consts.WEEKS_IN_MONTH == 0) //last week of the month == monthly event
    {
      //req = game.triggerEvent(portfolio);
      req = new TriggeredEventReq(eventFactory.getAnEvent());
      req.setID(ID);
      gameQ.add(req);
    }

    //Weekly events happen every week
    req = new TriggeredEventReq(eventFactory.getAnEvent());
    req.setID(ID);
    gameQ.add(req);
  }

  /**
   * Sends updated portfolio to client
   */
  public void sendPortfolio()
  {
    send(portfolio);
  }
}
